跳到主要内容

NodeJS 原生 Web服务

基本使用

Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,使用 HTTP 服务器或客户端功能必须调用 http 模块

如下,创建一个简单的访问服务器返回一串字符串

'use strict'
// 引入nodejs内置的http模块
let http = require('http')

// 创建并监听web服务器
http.createServer(function (request, response) {
let body = 'Hello World \n';

// 发送http头部
// 参数1: 响应码, 200表示成功
// 参数2: 响应头部信息, Content-Type内容类型:纯文本
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
"Content-Type": "text/html"
}).end(body)

}).listen(8888)

console.log('服务器运行在 http://localhost:8888');

注意这个 response.end() 方法

此方法向服务器发出信号,表明已发送所有响应头和主体,该服务器应该视为此消息已完成。 必须在每个响应上调用此 response.end() 方法

如果指定了 data,则相当于调用 response.write(data, encoding) 之后再调用 response.end(callback)

response.end('Hello World \n')

// 等价于
response.end(function(){
response.write('Hello World', 'utf8')
})

如果指定了 callback,则当响应流完成时将调用它。

访问文件

涉及到访问文件需要引入 fsurl 模块

var http = require('http');
var fs = require('fs');
var url = require('url');


// 创建服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;

// 输出请求的文件名
console.log("Request for " + pathname + " received.");

// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/html
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/html
response.writeHead(200, {'Content-Type': 'text/html'});

// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
});
}).listen(8080);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8080/');

设置响应头

response.writeHead(statusCode[, statusMessage][, headers])

此方法只能在消息上调用一次,并且必须在调用 response.end() 之前调用。返回对 ServerResponse 的引用,以便可以 链式调用

向请求发送响应头。 状态码是一个 3 位的 HTTP 状态码,如 200 第二个参数 headers 是响应头。

const body = 'hello world';
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
}).end(body);

NodeJS 项目热更新

nodemon 可以随时监听文件的变更,自动重启服务,总之就是 node 服务器开发用的工具

npm install -g nodemon

使用时只需使用它来启动服务就行了

nodemon index.js

References